<?php

namespace Ltt;

class Rc4Code
{
    //加解密密钥（随机字符串自定义）
    private $key = '_223c*(+d452sfd!@$#@)232($#@fg';

    /**
     * RC4加密算法函数
     * @param string $data 加密字符串
     * @param string $type 数据格式(16进制，base64)
     * @return string 返回加密后的字符串
     */
    public function encode($data, $type = '16')
    {
        $data = strval($data);
        if (empty($data)) {
            return '';
        }

        if ($type == '16') {
            return bin2hex($this->aes($this->key, $data));
        } else if ($type == 'base64') {
            return base64_encode($this->aes($this->key, $data));
        }

        return '';
    }

    /**
     * RC4解密算法函数
     * @param string $data 解密字符串
     * @param string $type 数据格式(16进制，base64)
     * @return string 返回解密后的字符串
     */
    public function decode($data, $type = '16')
    {
        $data = strval($data);
        if (empty($data)) {
            return '';
        }

        if ($type == '16') {
            if (preg_match('#^[A-Fa-f0-9]+$#', $data)) {
                return $this->aes($this->key, hex2bin($data));
            }
        } else if ($type == 'base64') {
            return $this->aes($this->key, base64_decode($data));
        }

        return '';
    }

    /**
     *RC4加密解密算法函数
        * @param string $pwd 秘钥
        * @param string $data 解密字符串
        * @return string 二进制数
        */
    private function aes($pwd, $data)
    {
        $key = $box = [];
        $pwd_length = strlen($pwd);
        $data_length = strlen($data);

        for ($i = 0; $i < 256; $i++) {
            $key[$i] = ord($pwd[$i % $pwd_length]);
            $box[$i] = $i;
        }

        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $key[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }

        $cipher = '';
        for ($a = $j = $i = 0; $i < $data_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;

            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;

            $k = $box[(($box[$a] + $box[$j]) % 256)];
            $cipher .= chr(ord($data[$i]) ^ $k);
        }

        return $cipher;
    }
}


